const requestHelper = require('../../utils/request');
const buildUrl = requestHelper.buildUrl || ((url) => url);

Page({
  data: {
    notificationEnabled: true,
    cacheSize: '0KB'
  },

  onLoad() {
    this.loadNotificationSettings();
    this.getCacheSize();
  },

  async loadNotificationSettings() {
    const app = getApp();
    const userId = app.globalData.userId;
    if (!userId) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    try {
      const res = await this.request({
        url: `/api/users/${userId}/notification-settings`,
        method: 'GET'
      });
      if (res && res.success && res.data) {
        this.setData({
          notificationEnabled: !!res.data.enabled
        });
      }
    } catch (e) {
      console.error('加载通知设置失败:', e);
    }
  },

  getCacheSize() {
    wx.getStorageInfo({
      success: (res) => {
        const sizeKB = Math.round(res.currentSize);
        this.setData({
          cacheSize: sizeKB < 1024 ? `${sizeKB}KB` : `${(sizeKB / 1024).toFixed(1)}MB`
        });
      }
    });
  },

  onNotificationChange(e) {
    const enabled = e.detail.value;
    this.setData({ notificationEnabled: enabled });

    const app = getApp();
    const userId = app.globalData.userId;
    if (!userId) return;

    this.request({
      url: `/api/users/${userId}/notification-settings`,
      method: 'POST',
      data: { enabled }
    }).catch((err) => {
      console.error('更新通知设置失败:', err);
      wx.showToast({ title: '保存失败', icon: 'none' });
    });
  },

  goToPrivacy() {
    wx.navigateTo({ url: '/pages/profile/privacySettings' });
  },

  clearCache() {
    const that = this;
    wx.showModal({
      title: '清理缓存',
      content: `确定要清理${this.data.cacheSize}缓存吗？`,
      success(res) {
        if (res.confirm) {
          wx.clearStorage({
            success: () => {
              that.setData({ cacheSize: '0KB' });
              wx.showToast({ title: '缓存清理成功' });
            },
            fail: () => {
              wx.showToast({ title: '清理失败', icon: 'none' });
            }
          });
        }
      }
    });
  },

  request(options) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: buildUrl(options.url || ''),
        method: options.method || 'GET',
        data: options.data,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => resolve(res.data),
        fail: reject
      });
    });
  }
});
